﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Ini;
using Finisar.SQLite;//Sqlite
using System.Net.Sockets;
using Socket_Connect;

using System.Net;
using System.IO;
using System.Threading;
using MySql.Data.MySqlClient;

namespace Qagent
{
    public partial class QagentForm : Form
    {
        public QagentForm()
        {
            InitializeComponent();
        }

        #region Sqlite
        MySqlConnection DBConn;
        MySqlCommand DBCmd;
        MySqlDataReader DBDataReader;
        #endregion

        string djdatFileName;
        string SN;
        bool AutoStart;

        //將cache List 匯入doc

        public void reloadDefList()
        {
            listBoxDjdat.Items.Clear();
            DirectoryInfo dirInfo = new DirectoryInfo(textBoxDocPath.Text);
            FileInfo[] fi = dirInfo.GetFiles("*.Djdat");

            foreach (FileInfo fiTemp in fi)
            {
                if (fiTemp.Name.Substring(0, 2) != "~$")
                {
                    listBoxDjdat.Items.Add(fiTemp.FullName);
                }
            }
        }


        #region commonFunction

        private void textBoxSelectFolder_Click(object sender, EventArgs e)
        {
            getPath(sender);

        }
        private void getPath(object sender)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                ((TextBox)(sender)).Text = folderBrowserDialog1.SelectedPath;
            }
        }
        #endregion

        #region From function
        tinSocket t1;

        private void buttonSendSocket_Click(object sender, EventArgs e)
        {




        }

        private void DocCenterForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            Properties.Settings.Default.Save();
        }

        #endregion



        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }


        #region Ftp
        string FtpFile;
        public string FtpUpload(string FtpAddress, string FileName, string UserName, string PW)
        {

            FtpFile = FileName;
            writeLog(FtpFile, "啟始上傳");
            toolStripLabelSocket.Text = "傳送狀態：上傳中";
            try
            {
                WebClient request = new WebClient();
                request.Credentials = new NetworkCredential(UserName, PW);
                System.Uri u1 = new Uri(FtpAddress + Path.GetFileName(FileName));

                request.UploadFileCompleted += new UploadFileCompletedEventHandler(UpLoadCompleted);
                request.UploadFileAsync(u1, FileName);
            }
            catch (Exception)
            {

                return FileName + ":上傳失敗";
            }

            return FileName + ":上傳成功";
        }

        public string FtpDownload(string FtpAddress, string FileName, string UserName, string PW)
        {

            FtpFile = FileName;
            writeLog(FtpFile, "啟始上傳");
            toolStripLabelSocket.Text = "傳送狀態：上傳中";
            try
            {
                WebClient request = new WebClient();
                request.Credentials = new NetworkCredential(UserName, PW);
                System.Uri u1 = new Uri(FtpAddress + Path.GetFileName(FileName));
                request.DownloadFileCompleted += new AsyncCompletedEventHandler(DownLoadCompleted);
                request.DownloadFileAsync(u1, FileName);

            }
            catch (Exception)
            {

                return FileName + ":上傳失敗";
            }

            return FileName + ":上傳成功";
        }

        void UpLoadCompleted(object sender, UploadFileCompletedEventArgs e)
        {
            writeLog(FtpFile, "Ftp上傳成功");
            toolStripLabelSocket.Text = "Ftp傳送狀態：閒置";
        }
        void DownLoadCompleted(object sender, AsyncCompletedEventArgs e)
        {
            writeLog(FtpFile, "下載成功");
            toolStripLabelSocket.Text = "傳送狀態：閒置";
        }

        #endregion

        public void writeLog(string FileName, string status)
        {
            DBConn.Open();
            DBCmd = DBConn.CreateCommand();
            DBCmd.CommandText = "insert into mappingLog (SN, FileName , FileType , Status , EventTime) values(@SN, @FileName , @FileType , @Status , @EventTime)";
            DBCmd.Parameters.Add("@SN", "SN" + DateTime.Now.ToString("yyMMddhhmmssfff"));
            DBCmd.Parameters.Add("@FileName", FileName);
            DBCmd.Parameters.Add("@FileType", Path.GetExtension(FileName));
            DBCmd.Parameters.Add("@Status", status);
            DBCmd.Parameters.Add("@EventTime", DateTime.Now.ToString());

            DBCmd.ExecuteNonQuery();
            DBConn.Close();
        }

        public void writeLog(string FileName, string status, string SourceFile)
        {
            DBConn.Open();
            DBCmd = DBConn.CreateCommand();
            DBCmd.CommandText = "insert into mappingLog (SN, FileName , FileType , Status ,SourceFile, EventTime,BranchID) values(@SN, @FileName , @FileType , @Status ,@SourceFile, @EventTime,@BranchID)";
            DBCmd.Parameters.Add("@SN", "SN" + DateTime.Now.ToString("yyMMddhhmmssfff"));
            DBCmd.Parameters.Add("@FileName", FileName);
            DBCmd.Parameters.Add("@FileType", Path.GetExtension(FileName));
            DBCmd.Parameters.Add("@Status", status);
            DBCmd.Parameters.Add("@SourceFile", Path.GetFileName(SourceFile));
            DBCmd.Parameters.Add("@EventTime", DateTime.Now.ToString());
            DBCmd.Parameters.Add("@BranchID", Path.GetFileName(SourceFile).Substring(0, 4));

            DBCmd.ExecuteNonQuery();
            DBConn.Close();
        }

        public void writeMapStatus(string FileName)
        {
            FileStream m_filestream = new FileStream(FileName, FileMode.Open, FileAccess.Read);
            Byte[] m_byte = new Byte[m_filestream.Length];
            m_filestream.Read(m_byte, 0, m_byte.Length);
            SQLiteParameter param_m = new SQLiteParameter("@idimage", DbType.Binary);//

            DBConn.Open();
            DBCmd = DBConn.CreateCommand();
            DBCmd.CommandText = "insert into mappingStatus (SN,MainStatus, DJDat , DJDatStatus,DjdatFile , BranchID) values(@SN, @MainStatus , @DJDat , @DJDatStatus ,@DjdatFile,@BranchID)";
            string sn = "SN" + DateTime.Now.ToString("yyMMddhhmmssfff");
            DBCmd.Parameters.Add("@SN", "SN" + DateTime.Now.ToString("yyMMddhhmmssfff"));
            DBCmd.Parameters.Add("@SN", sn);
            DBCmd.Parameters.Add("@MainStatus", "datUpload");
            DBCmd.Parameters.Add("@DJDat", Path.GetFileName(FileName));
            DBCmd.Parameters.Add("@DJDatStatus", "已上傳");
            //            DBCmd.Parameters.Add(param_m);

            DBCmd.Parameters.Add("@djdatFile", DbType.Binary);//, m_byte.Length, ParameterDirection.Input, false, 0, 0, null, DataRowVersion.Current, m_byte);
            DBCmd.Parameters["@DjdatFile"].Value = m_byte;
            DBCmd.Parameters.Add("@BranchID", Path.GetFileName(FileName).Substring(0, 4));
            DBCmd.ExecuteNonQuery();
            DBConn.Close();
            m_filestream.Close();

            string backupFile = OutputPathtextBox.Text + "\\" + Path.GetFileName(FileName);
            if (File.Exists(OutputPathtextBox.Text + "\\" + Path.GetFileName(FileName)))
            {
                backupFile = OutputPathtextBox.Text + "\\" + Path.GetFileNameWithoutExtension(FileName) + DateTime.Now.ToString(".yyMMddhhmmssfff") + Path.GetExtension(FileName);
            }
            File.Move(FileName, backupFile);


        }

        public void updateMapStatus(string sn, string status)
        {

            DBConn.Open();
            DBCmd = DBConn.CreateCommand();
            DBCmd.CommandText = "update mappingStatus set MainStatus =@MainStatus,DocStatus=@DocStatus where SN=@SN ";
            DBCmd.Parameters.Add("@SN", sn);
            DBCmd.Parameters.Add("@MainStatus", status);
            DBCmd.Parameters.Add("@DocStatus", "ready");

            DBCmd.ExecuteNonQuery();
            DBConn.Close();

        }

        #region Msg Function

        public void LoadMsg()
        {
            string MsgSN = "";
            string titaString = "";

            DBConn.Open();
            DBCmd = DBConn.CreateCommand();
            DBCmd.CommandText = "select * from MessageQ where Status =@Status";
            int i = 0;
            DBCmd.Parameters.Add("@Status", i);
            DBDataReader = DBCmd.ExecuteReader();

            if (DBDataReader.Read())
            {
                MsgSN = DBDataReader["MsgSN"].ToString();
                titaString = DBDataReader["TITAMsg"].ToString();
            }
            DBConn.Close();

            sendTita(MsgSN, titaString);

            DBConn.Open();
            DBCmd = DBConn.CreateCommand();
            DBCmd.CommandText = "update MessageQ set Status = @Status,MsgDateTime = @MsgDateTime  where MsgSN =@MsgSN";
            DBCmd.Parameters.Add("@MsgSN", MsgSN);
            DBCmd.Parameters.Add("@Status", "1");
            DBCmd.Parameters.Add("@MsgDateTime", DateTime.Now.ToString("yyMMdd-hh:mm:ss"));
            DBCmd.ExecuteNonQuery();
            listBoxDjdat.Items.Add(DateTime.Now.ToString("yyMMdd-hh:mm:ss: ") + MsgSN + "已更新");
            DBConn.Close();



        }

        public void sendTita(string MsgSN, string TITAMsg)
        {

            listBoxDjdat.Items.Add(DateTime.Now.ToString("yyMMdd-hh:mm:ss: ") + MsgSN + "發送中 ");
            DBConn.Open();
            DBCmd = DBConn.CreateCommand();
            DBCmd.CommandText = "update MessageQ set Status = @Status  where MsgSN =@MsgSN";
            DBCmd.Parameters.Add("@MsgSN", MsgSN);
            DBCmd.Parameters.Add("@Status", "1");
            DBCmd.ExecuteNonQuery();
            listBoxDjdat.Items.Add(DateTime.Now.ToString("yyMMdd-hh:mm:ss: ") + MsgSN + "Tita送出");
            DBConn.Close();

            //call Send Tita
            string TotaMsg = "tota";
            DBConn.Open();
            DBCmd = DBConn.CreateCommand();
            DBCmd.CommandText = "update MessageQ set TotaMsg = @TotaMsg  where MsgSN =@MsgSN";
            DBCmd.Parameters.Add("@MsgSN", MsgSN);
            DBCmd.Parameters.Add("@TotaMsg", TotaMsg);
            DBCmd.ExecuteNonQuery();
            listBoxDjdat.Items.Add(DateTime.Now.ToString("yyMMdd-hh:mm:ss: ") + MsgSN + "接收Tota ");
            DBConn.Close();

        }

        #endregion



        private void toolStripButton3_Click_1(object sender, EventArgs e)
        {

            if (AutoStart)
            {
                AutoStart = false;
                toolStripButtonStartAuto.Image = imageListStart.Images[0];
            }
            else
            {
                AutoStart = true;
                toolStripButtonStartAuto.Image = imageListStart.Images[1];
            }

            timerStart.Enabled = AutoStart;

        }

        private void toolStripButton2_Click_1(object sender, EventArgs e)
        {
            //    t1 = new tinSocket();
            //    IPAddress _ServerIP = IPAddress.Parse(textBoxServerIP.Text);
            //    t1.BeginSend(_ServerIP, int.Parse(textBoxServerPort.Text), oTpath + " 已傳送 ");
        }

        private void timerStart_Tick(object sender, EventArgs e)
        {
            timerStart.Enabled = false;
            LoadMsg();
        }

        private void QagentForm_Load(object sender, EventArgs e)
        {
          //  DBConn = new SQLiteConnection("Data Source=" + textBoxDBFile.Text + ";Version=3;Compress=True;");
        }

        private void toolStripButtonStartAuto_Click(object sender, EventArgs e)
        {
            LoadMsg();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {


            DBConn = new MySqlConnection("server=djimage.myftp.org;User Id=svs;password=svs;database=test23");
            for (int i = 0; i < 10; i++)
            {
                DBConn.Open();
                DBCmd = DBConn.CreateCommand();
                DBCmd.CommandText = "insert into   tab23  (sn2) values(@sn2)";

                DBCmd.Parameters.Add("@sn2", "中文abc");
                DBCmd.ExecuteNonQuery();
                listBoxDjdat.Items.Add(i.ToString());
                DBConn.Close();
                Application.DoEvents();
            }
            
        }
    }
}
